﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using CDFWPUG.Model;

namespace CDFWPUG.Helpers
{
    public class RssHelper
    {
        private String _path;
        private List<FeedItem> _Feeds = new List<FeedItem>();
        public List<FeedItem> Feeds
        {
            get
            {
                return _Feeds;
            }
        }

        public RssHelper(String url)
        {
            _path = url;
        }

        public void LoadFeeds()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(_path));
        }

        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XElement _xml;
            try
            {
                if (!e.Cancelled)
                {
                    _xml = XElement.Parse(e.Result);
                    foreach (XElement item in _xml.Elements("channel").Elements("item"))
                    {
                        FeedItem _item = new FeedItem()
                        {
                            Title= item.Element("title").Value,
                            Description = Regex.Replace(item.Element("description").Value, @"<(.|n)*?>", String.Empty),
                            Link = item.Element("link").Value,
                            Guid = item.Element("guid").Value,
                            Published = DateTime.Parse(item.Element("pubDate").Value)
                        };

                        _Feeds.Add(_item);
                    }
                }
            }
            catch (Exception)
            {
                
              
            }
            

        }





    }
}
